﻿using System;
using System.Collections.Generic;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;

using com.stockstar.baseinfo.datacontract;
using System.Text;
using System.Net;
using System.IO;

public class F10Query
{
    //private static readonly string __baseUri = "http://192.168.13.200:8088/{0}/{1}/";
    private static readonly string __baseUri = System.Configuration.ConfigurationManager.AppSettings["CanalServerAddress"] + "{0}/{1}/";

    public static bool TryParse(string url, string query, bool isPost, out JToken jObjArray)
    {
        jObjArray = null;

        bool bRet = false;

        try
        {
            var data = string.Empty;

            if (isPost)
            {
                data = F10Query.Post(url, query, System.Text.Encoding.GetEncoding("gb2312"));
            }
            else
            {
                data = F10Query.Get(url.TrimEnd('/') + "/" + query + "&d=" + DateTime.Now.ToString("yyyyMMddHHmmss"), System.Text.Encoding.GetEncoding("gb2312"));
            }
            if (data != null && data.Length > 0)
            {
                var o = JObject.Parse(data);

                bRet = o != null && o["rows"] != null && o["rows"].HasValues && o["total_rows"] != null;

                jObjArray = o["rows"];
            }
        }
        catch (Exception ex)
        {
            bRet = false;
        }

        return bRet;
    }

    public static bool TryParse(string url, string query, bool isPost, out JToken jObjArray, out int total)
    {
        jObjArray = null;

        bool bRet = false;

        total = 0;

        try
        {
            var data = string.Empty;

            if (isPost)
            {
                data = F10Query.Post(url, query, System.Text.Encoding.GetEncoding("gb2312"));
            }
            else
            {
                data = F10Query.Get(url.TrimEnd('/') + "/" + query + "&d=" + DateTime.Now.ToString("yyyyMMddHHmmss"), System.Text.Encoding.GetEncoding("gb2312"));
            }
            if (data != null && data.Length > 0)
            {
                var o = JObject.Parse(data);

                bRet = o != null && o["rows"] != null && o["rows"].HasValues && o["total_rows"] != null;

                total = (int)o["total_rows"];

                jObjArray = o["rows"];
            }
        }
        catch (Exception ex)
        {
            bRet = false;
        }

        return bRet;
    }

    public static List<FundCode> GetFundCodeByTotal()
    {
        var parm = "field=FUND_CODE,FUNDSNAME,FND_TYPE,INVST_TYPE,UNIT_NET,FUND_STATUS&full=2&sort=FUND_CODE%20asc&limit={0}";
        Newtonsoft.Json.Linq.JToken __jObjectArray = null;
        var total = 0;
        var lists = new List<FundCode>();
        if (F10Query.TryParse(string.Format(__baseUri, "base", "V_JRJ_FUND_NET_LASTDAY"), string.Format(parm, 1), false, out __jObjectArray, out total)
            && F10Query.TryParse(string.Format(__baseUri, "base", "V_JRJ_FUND_NET_LASTDAY"), string.Format(parm, total), false, out __jObjectArray)
            )
        {
            foreach (var item in __jObjectArray)
            {
                lists.Add(new FundCode()
                {
                    Code = (string)item["FUND_CODE"],
                    SimpleName = (string)item["FUNDSNAME"],
                    FundType = item.J_Integer("FND_TYPE", 0),
                    InvestType = item.J_Integer("INVST_TYPE", 0), 
                });
            }
        }
        return lists;
    }

    public static String Get(string url, Encoding encoding)
    {
        string strResult = "";
        try
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 30000;
            request.Method = "GET";
            request.Headers.Set("Pragma", "no-cache");
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            using (Stream streamReceive = response.GetResponseStream())
            using (StreamReader streamReader = new StreamReader(streamReceive, encoding))
            {
                strResult = streamReader.ReadToEnd();
            }
        }
        catch
        {
            strResult = string.Empty;
        }
        return strResult;
    }

    public static String Post(string url, string param, Encoding encoding)
    {
        string strResult = "";
        try
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            byte[] bs = Encoding.ASCII.GetBytes(param);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 30000;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bs.Length;
            request.Headers.Set("Pragma", "no-cache");
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bs, 0, bs.Length);
            }
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            using (Stream streamReceive = response.GetResponseStream())
            using (StreamReader streamReader = new StreamReader(streamReceive, encoding))
            {
                strResult = streamReader.ReadToEnd();
            }
        }
        catch
        {
            strResult = string.Empty;
        }
        return strResult;
    }

    public static bool TryParse(F10ParamEntity param, bool isPost, out JToken jObjArray, out int total)
    {
        jObjArray = null;

        bool bRet = false;

        total = 0;

        try
        {
            var data = string.Empty;

            var url = string.Format(F10Query.__baseUri, param.Prefix, param.TableName);

            var query = param.ToString();

            if (isPost)
            {
                data = F10Query.Post(url, query, System.Text.Encoding.GetEncoding("gb2312"));
            }
            else
            {
                data = F10Query.Get(url.TrimEnd('/') + "/" + query + "&d=" + DateTime.Now.ToString("yyyyMMddHHmmss"), System.Text.Encoding.GetEncoding("gb2312"));
            }
            if (data != null && data.Length > 0)
            {
                var o = JObject.Parse(data);

                bRet = o != null && o["rows"] != null && o["rows"].HasValues && o["total_rows"] != null;

                total = (int)o["total_rows"];

                jObjArray = o["rows"];
            }
        }
        catch (Exception ex)
        {
            bRet = false;
        }

        return bRet;
    }
}